package com.example.demo.core;

import com.example.demo.domain.Goods;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

/**
 * @author Shanks
 * @date 2020-05-26
 */
@Component
public class HtmlParseUtils {

    public static void main(String[] args) throws IOException {
        System.out.println(new HtmlParseUtils().getGoodsListFromJd("java").get(0));
    }

    public List<Goods> getGoodsListFromJd(String keyword) throws IOException {
        // https://search.jd.com/Search?keyword=java&enc=utf-8
        String url = "https://search.jd.com/Search?keyword=" + keyword + "&enc=utf-8";
        Document document = Jsoup.parse(new URL(url), 200000);
        Element element = document.getElementById("J_goodsList");
        Elements elements = element.getElementsByTag("li");

        List<Goods> list = new ArrayList<>();
        for (Element el : elements) {

            String sku = el.attributes().get("data-sku");

            String img = el.getElementsByTag("img").eq(0).attr("src");

            String imgLazy = el.getElementsByTag("img").eq(0).attr("source-data-lazy-img");

            String price = el.getElementsByClass("p-price").eq(0).text();

            String title = el.getElementsByClass("p-name").eq(0).text();

            String shop = el.getElementsByClass("J_im_icon").eq(0).text();

            Goods goods = new Goods();
            goods.setSku(sku);
            goods.setTitle(title);
            goods.setImg(img);
            goods.setImgLazy(imgLazy);
            goods.setPrice(price);
            goods.setShop(shop);
            list.add(goods);
        }
        return list;
    }
}